///////////////////////////////////////////////////////////////////////////////
// Name:        wxAutoComboBox.cpp
// Purpose:     wxAutoComboBox class implementation.
// Author:      Guru Kathiresan
// Modified by: Ville Lindell <vdell@users.sf.net>
// Created:     03/24/2006
// Copyright:   (c) Guru Kathiresan
// Licence:     BSD licence
///////////////////////////////////////////////////////////////////////////////

#include "stdafx.hpp"
#include "wxAutoCombobox.hpp"

IMPLEMENT_DYNAMIC_CLASS ( wxAutoComboBox, wxComboBox )

wxAutoComboBox::wxAutoComboBox()
{
	Connect ( -1, wxEVT_KEY_UP, wxKeyEventHandler ( wxAutoComboBox::OnKeyUp ) );
}

wxAutoComboBox::wxAutoComboBox ( wxWindow *pParent, wxWindowID id, 
								const wxString &rValue, const wxPoint &rPos, 
								const wxSize &rSize, wxInt32 n, const wxString *pChoices, 
								long style, const wxValidator &rValidator, 
								const wxString &rName ) : wxComboBox ( pParent, id,
								rValue, rPos, rSize, n, pChoices, style, rValidator, rName )
{
	Connect ( id, wxEVT_KEY_UP, wxKeyEventHandler ( wxAutoComboBox::OnKeyUp ) );
}

void wxAutoComboBox::OnKeyUp ( wxKeyEvent &rEvent )
{
	if ( IsAutoCompleteEnabled() )
	{
		const wxInt32 key_code = rEvent.GetKeyCode();

		if ( ( ( key_code >= 32 ) && ( key_code <= 126 ) ) || 
			( ( key_code >= 128 ) && ( key_code <= 254 ) ) )
		{
			const wxString value ( GetValue() );

			long start = -1, end = -1;
			GetSelection ( &start, &end );

			const wxString entered_value ( value.Left ( start ) );
			wxInt32 idx = -1;
			for ( size_t i = 0; i < GetCount(); i++ )
			{
				if ( GetString(i).Left ( entered_value.length() ) == entered_value )
				{
					idx = ( wxInt32 ) i;
					break;
				}                     
			}
			if ( idx != -1 )
			{
				SetSelection ( idx );
				SetSelection ( start, GetValue().length() );                       
				return;
			}              
		}
	}
	rEvent.Skip();
}
